package com.haitaoit.chengquan.module.home.activity.zhaopin;

import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.module.center.model.ProvinceBase;
import com.haitaoit.chengquan.module.center.model.area;
import com.haitaoit.chengquan.module.home.model.RecruitModel;
import com.haitaoit.chengquan.module.home.model.TitleModel;
import com.haitaoit.chengquan.module.login.LoginActivity;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.utils.Utils;
import com.haitaoit.chengquan.view.pickerview.OptionsPopupWindow;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class JobSendActivity extends BaseActivity {
    @ViewInject(R.id.job_send_type)
    TextView job_send_type;
    @ViewInject(R.id.job_send_time_long)
    TextView job_send_time_long;
    @ViewInject(R.id.job_send_school)
    TextView job_send_school;
    @ViewInject(R.id.job_send_address)
    TextView job_send_address;
    @ViewInject(R.id.job_send_money)
    TextView job_send_money;
    @ViewInject(R.id.job_send_history)
    EditText job_send_history;
    @ViewInject(R.id.job_title)
    EditText job_title;
    @ViewInject(R.id.job_name)
    EditText job_name;
    @ViewInject(R.id.job_phone)
    EditText job_phone;

    private List<ProvinceBase> province;
    private List<com.haitaoit.chengquan.module.center.model.city> city;
    private List<area> region;

    private ArrayList<String> options1Items = new ArrayList<String>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<ArrayList<String>>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<ArrayList<ArrayList<String>>>();

    private String zwid = "", jyid = "", xlid = "", gwid = "";
    private RecruitModel model;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_job_send);
        setTitle_V("发布求职");
        setLeftShow(1, R.mipmap.left);
        backLeft_V();
        ViewUtils.inject(this);

        httpGetjob_configuration_list();
    }

    @OnClick({R.id.job_send_type, R.id.job_send_time_long, R.id.job_send_school,
            R.id.job_send_address, R.id.job_send_money, R.id.job_send})
    public void onClick(View v) {
        // 收起键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        switch (v.getId()) {
            case R.id.job_send_type:// 类别
                if (model.getJob_categorylist() == null || model.getJob_categorylist().size() == 0) {
                    ToastUtils.showToast("暂无选项！");
                } else {
                    SelectType(model.getJob_categorylist());
                }
                break;
            case R.id.job_send_time_long:// 工作年限
                if (model.getExperience_requirements_list_dy() == null || model.getExperience_requirements_list_dy().size() == 0) {
                    ToastUtils.showToast("暂无选项！");
                } else {
                    SelectJingyan(model.getExperience_requirements_list_dy());
                }
                break;
            case R.id.job_send_school:// 学历
                if (model.getEducation_list() == null || model.getEducation_list().size() == 0) {
                    ToastUtils.showToast("暂无选项！");
                } else {
                    SelectXueli(model.getEducation_list());
                }
                break;
            case R.id.job_send_address:// 工作地点
                options1Items = new ArrayList<String>();
                options2Items = new ArrayList<ArrayList<String>>();
                options3Items = new ArrayList<ArrayList<ArrayList<String>>>();
                InputStream inputStream = getResources().openRawResource(R.raw.region);
                province(inputStream);
                OptionsPopupWindow pwOptions = new OptionsPopupWindow(this, "选择地区");// 地址选择器
                pwOptions.setPicker(options1Items, options2Items, options3Items, true);// 三级联动效果
                pwOptions.setSelectOptions(0, 0, 0);// 设置默认选中的三级项目
                // 监听确定选择按钮
                pwOptions.setOnoptionsSelectListener(new OptionsPopupWindow.OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3) {
                        // 返回的分别是三个级别的选中位置
                        String tx = options1Items.get(options1) + ","
                                + options2Items.get(options1).get(option2) + ","
                                + options3Items.get(options1).get(option2).get(options3);
                        job_send_address.setText(tx);
                    }
                });
                pwOptions.showAtLocation(LayoutInflater.from(this).inflate(R.layout.activity_job_send, null),
                        Gravity.BOTTOM, ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
                break;
            case R.id.job_send_money:// 薪资
                if (model.getPost_salary_list_dy() == null || model.getPost_salary_list_dy().size() == 0) {
                    ToastUtils.showToast("暂无选项！");
                } else {
                    SelectGangwei(model.getPost_salary_list_dy());
                }
                break;
            case R.id.job_send:// 发布
                if (PreferenceUtils.getPrefString("user_id", "").equals("")) {
                    Intent intent = new Intent(this, LoginActivity.class);
                    intent.putExtra("tag", "0");
                    startActivity(intent);
                } else if (PreferenceUtils.getPrefString("account_type", "").equals("1")) {
                    if (job_title.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入求职标题！");
                    } else if (zwid.equals("")) {
                        ToastUtils.showToast("请选择职位类别！");
                    } else if (job_name.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入名称！");
                    } else if (!Utils.isMobileNum(job_phone.getText().toString())) {
                        ToastUtils.showToast("手机号格式有误请重新输入！");
                    } else if (job_send_time_long.getText().toString().equals("")) {
                        ToastUtils.showToast("请选择工作年限！");
                    } else if (job_send_school.getText().toString().equals("")) {
                        ToastUtils.showToast("请选择学历要求！");
                    } else if (job_send_address.getText().toString().equals("")) {
                        ToastUtils.showToast("请选择期望工作地点！");
                    } else if (job_send_money.getText().toString().equals("")) {
                        ToastUtils.showToast("请选择期望薪资！");
                    } else if (job_send_history.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入工作经历！");
                    } else {
                        httpadd_job_information();
                    }
                } else {
                    ToastUtils.showToast("需求商才可以发布求职！");
                }
                break;
        }
        super.onClick(v);
    }

    // 发布招聘信息
    private void httpadd_job_information() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));

        //TODO:这里就增加了一个
        list.add(new NameValuePairSign("id", "0"));

        String sign = GetSign.genPackageSign(list);


        String url = Constant.add_job_information
                +"id=0"
                + "&user_id=" + PreferenceUtils.getPrefString("user_id", "")
                + "&sign=" + sign;

        JSONObject json = new JSONObject();
        try {
            json.put("title", job_title.getText().toString());
            json.put("job_category", zwid);
            json.put("name", job_name.getText().toString());
            json.put("phone", job_phone.getText().toString());
            json.put("work_year", jyid);
            json.put("education", xlid);
            json.put("expect_work_place", job_send_address.getText().toString());
            json.put("expected_salary", gwid);
            json.put("work_experience", job_send_history.getText().toString());
        } catch (JSONException e1) {
            e1.printStackTrace();
        }

        HttpUtilsSingle.doPost(this, false, url, json, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            ToastUtils.showToast(Errmsg);
                            //                            setResult(1);
                            finish();
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    // 获取发布招聘或求职配置信息
    private void httpGetjob_configuration_list() {
        int i = (int) Math.floor(Math.random() * 9000 + 1000);
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("rnd", i + ""));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("rnd", i + "");
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getjob_configuration_list, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            model = gson.fromJson(Response, RecruitModel.class);
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    // 职位类别
    private void SelectType(final List<TitleModel> list) {
        final ArrayList<String> list2 = new ArrayList<String>();
        for (int i = 0; i < list.size(); i++) {
            list2.add(list.get(i).getName());
        }

        OptionsPopupWindow popSex = new OptionsPopupWindow(this, "职位类别");
        popSex.setPicker(list2);
        popSex.setSelectOptions(0);
        popSex.setOnoptionsSelectListener(new OptionsPopupWindow.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                job_send_type.setText(list2.get(options1));
                zwid = list.get(options1).getId();
                System.out.println();
            }
        });
        popSex.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);// popupwindow消失的时候恢复成原来的透明度
            }
        });
        popSex.showAtLocation(job_send_type, Gravity.BOTTOM, 0, 0);
        backgroundAlpha(0.6f);
    }

    // 经验要求
    private void SelectJingyan(final List<TitleModel> list) {
        final ArrayList<String> list2 = new ArrayList<String>();
        for (int i = 0; i < list.size(); i++) {
            list2.add(list.get(i).getName());
        }

        OptionsPopupWindow popSex = new OptionsPopupWindow(this, "经验要求");
        popSex.setPicker(list2);
        popSex.setSelectOptions(0);
        popSex.setOnoptionsSelectListener(new OptionsPopupWindow.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                job_send_time_long.setText(list2.get(options1));
                jyid = list.get(options1).getId();
            }
        });
        popSex.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);// popupwindow消失的时候恢复成原来的透明度
            }
        });
        popSex.showAtLocation(job_send_time_long, Gravity.BOTTOM, 0, 0);
        backgroundAlpha(0.6f);
    }

    // 学历要求
    private void SelectXueli(final List<TitleModel> list) {
        final ArrayList<String> list2 = new ArrayList<String>();
        for (int i = 0; i < list.size(); i++) {
            list2.add(list.get(i).getName());
        }

        OptionsPopupWindow popSex = new OptionsPopupWindow(this, "学历要求");
        popSex.setPicker(list2);
        popSex.setSelectOptions(0);
        popSex.setOnoptionsSelectListener(new OptionsPopupWindow.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                job_send_school.setText(list2.get(options1));
                xlid = list.get(options1).getId();
            }
        });
        popSex.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);// popupwindow消失的时候恢复成原来的透明度
            }
        });
        popSex.showAtLocation(job_send_school, Gravity.BOTTOM, 0, 0);
        backgroundAlpha(0.6f);
    }

    // 学历要求
    private void SelectGangwei(final List<TitleModel> list) {
        final ArrayList<String> list2 = new ArrayList<String>();
        for (int i = 0; i < list.size(); i++) {
            list2.add(list.get(i).getName());
        }

        OptionsPopupWindow popSex = new OptionsPopupWindow(this, "岗位薪资");
        popSex.setPicker(list2);
        popSex.setSelectOptions(0);
        popSex.setOnoptionsSelectListener(new OptionsPopupWindow.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                job_send_money.setText(list2.get(options1));
                gwid = list.get(options1).getId();
            }
        });
        popSex.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);// popupwindow消失的时候恢复成原来的透明度
            }
        });
        popSex.showAtLocation(job_send_money, Gravity.BOTTOM, 0, 0);
        backgroundAlpha(0.6f);
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha;// 0.0-1.0
        getWindow().setAttributes(lp);
    }

    /**
     * @param inputStream
     * @tab 解析从本地获取的json
     */
    private void province(InputStream inputStream) {
        String a = getString(inputStream);
        try {
            JSONObject jsondata = new JSONObject(a);
            Gson gson = new Gson();
            province = gson.fromJson(jsondata.getString("data"),
                    new TypeToken<List<ProvinceBase>>() {
                    }.getType());
            //            Log.e("tag", province.toString());
            ArrayList<String> options2Items_i = null;
            ArrayList<ArrayList<String>> options3Items_j = null;
            for (int i = 0; i < province.size(); i++) {
                options1Items.add(province.get(i).getName());
                city = province.get(i).getCity();
                options2Items_i = new ArrayList<String>();
                options3Items_j = new ArrayList<ArrayList<String>>();
                for (int j = 0; j < city.size(); j++) {
                    options2Items_i.add(city.get(j).getName());
                    region = city.get(j).getArea();
                    ArrayList<String> options3Items_j_j2 = new ArrayList<String>();
                    for (int j2 = 0; j2 < region.size(); j2++) {
                        options3Items_j_j2.add(region.get(j2).getName());
                    }
                    options3Items_j.add(options3Items_j_j2);
                }
                options2Items.add(options2Items_i);
                options3Items.add(options3Items_j);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public static String getString(InputStream inputStream) {
        InputStreamReader inputStreamReader = null;
        try {
            inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        BufferedReader reader = new BufferedReader(inputStreamReader);
        StringBuffer sb = new StringBuffer("");
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

}
